//
//  WDGoutReviewVehicleViewController.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/14.
//

#import "WDGoutReviewVehicleViewController.h"
#import "WDGoutReviewVehicleViewModel.h"
#import "WDWorderOrderWaitVehicleTopView.h"
#import "WDGoutWaitVehicleBottomView.h"
#import "WDWorkOrderProcessModeView.h"
#import "TYZPlaceholderTextView.h"
#import "WDGoutReviewVehicleRemarkImageView.h" // 备注图片
#import "AuthorityManager.h"

@interface WDGoutReviewVehicleViewController () <UITextViewDelegate, UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) WDGoutReviewVehicleViewModel *viewModel;

@property (nonatomic, strong) WDWorderOrderWaitVehicleTopView *topView;

/// 处理方式视图
@property (nonatomic, strong) WDWorkOrderProcessModeView *processModeView;

/// 处理说明标题
@property (nonatomic, strong) UILabel *remarkLabel;

/// 处理说明输入框
@property (nonatomic, strong) TYZPlaceholderTextView *remarkView;

/// 备注图片
@property (nonatomic, strong) WDGoutReviewVehicleRemarkImageView *remarkImageView;


@property (nonatomic, strong) WDGoutWaitVehicleBottomView *bottomView;

@end

@implementation WDGoutReviewVehicleViewController

- (void)dealloc {
    debugMethod();
    
}

- (void)initWithVar {
    [super initWithVar];
    
}

- (void)initWithViewModel {
    _viewModel = [WDGoutReviewVehicleViewModel new];
    _viewModel.serviceModel = self.serviceModel;
    [_viewModel setupData];
}

- (void)initWithNavBar {
    [super initWithNavBar];
    
    [self initWithBackButton];
    
    self.navigationItem.title = self.viewModel.title;
    
    [self initWithNavRight];
}

- (void)initWithSubView {
    [super initWithSubView];
    
    [self initWithRootContent:NO];
    self.rootContent.height = self.rootContent.height - TABBAR_HEIGHT;
    
    [self initWithTopView];
    
    [self initWithBottomView];
    
    if ([[EDSAppDelegateTool sharedInstance] hasPermission:@(10020302) parentCode:@(100203)]) {
        [self initWithProcessModeView];
        
        /// 处理说明标题
        [self initWithRemarkLabel];

        /// 处理说明输入框
        [self initWithRemarkView];
        
        // 备注图片
        [self initWithRemarkImageView];
        
        self.rootContent.contentSize = CGSizeMake(kScreenW, self.remarkImageView.bottom + 20);
    }
    
    

}

- (void)initWithNavRight {
    if (![[EDSAppDelegateTool sharedInstance] hasScanCode]) {
        return;
    }
    UIImage *image = [UIImage imageNamed:@"ic_nav_scan_code"];
    CGRect frame = CGRectMake(0, 0, 30, 30);
    UIButton *btnRight = [UIButton createWithButton:nil frame:frame font:FONTSIZE(16) target:self action:@selector(actionWithNavRight:) propertiesBlock:^(UIButton * _Nonnull button) {
        [button setImage:image forState:UIControlStateNormal];
    }];
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
//    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initWithTopView {
    if (!_topView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, kWDWorderOrderWaitVehicleTopViewHeight);
        _topView = [[WDWorderOrderWaitVehicleTopView alloc] initWithFrame:frame];
        _topView.hiddenApplyCancel = ![[EDSAppDelegateTool sharedInstance] hasPermission:@(10020303) parentCode:@(100203)];
        [self.rootContent addSubview:_topView];
        
        @weakify(self);
        _topView.touchDetailBlock = ^{
            @strongify(self);
            [self actionWithDetail];
        };
        _topView.touchApplyCancelBlock = ^{
            @strongify(self);
            [self actionWithApplyCancel:nil];
        };
    }
    [_topView updateWithViewData:self.viewModel.serviceModel];
}

- (void)initWithProcessModeView {
    if (!_processModeView) {
        CGRect frame = CGRectMake(0, self.topView.bottom, kScreenW, kWDWorkOrderProcessModeViewHeight);
        _processModeView = [[WDWorkOrderProcessModeView alloc] initWithFrame:frame];
        [self.rootContent addSubview:_processModeView];
        
        @weakify(self);
        _processModeView.viewBlock = ^(TYZCommonCellModel *data) {
            @strongify(self);
            if ([data.title isEqualToString:@"调件维修"]) {
                self.bottomView.hiddenRight = YES;
            } else {
                self.bottomView.hiddenRight = NO;
            }
        };
    }
    [self.processModeView updateWithViewData:self.viewModel];
}

/// 处理说明标题
- (void)initWithRemarkLabel {
    if (!_remarkLabel) {
        CGRect frame = CGRectMake(25, self.processModeView.bottom + 8, kScreenW - 32, 20);
        _remarkLabel = [UILabel createWithLabel:self.rootContent frame:frame font:[UIFont systemFontOfSize:14 weight:UIFontWeightMedium] propertiesBlock:^(UILabel * _Nonnull label) {
            label.text = @"处理说明";
        }];
        
        CGRect lframe = CGRectMake(20, 0, 2, 10);
        CALayer *line = [CALayer drawLine:self.rootContent frame:lframe lineColor:kThemeColor];
        line.centerY = self.remarkLabel.centerY;
    }
    _remarkLabel.attributedText = [EDSUtility attributeTitle:@"建议处理说明" titleColor:[UIColor colorWithHexString:@"#000000"] titleFont:[UIFont systemFontOfSize:14 weight:UIFontWeightRegular] value:@" *" valueColor:[UIColor colorWithHexString:@"#F24C55"] valueFont:[UIFont systemFontOfSize:14 weight:UIFontWeightRegular]];
}

/// 处理说明输入框
- (void)initWithRemarkView {
    if (!_remarkView) {
        CGRect frame = CGRectMake(16, self.remarkLabel.bottom + 8, self.remarkLabel.width, 130);
        _remarkView = [[TYZPlaceholderTextView alloc] initWithFrame:frame];
        _remarkView.font = FONT_Regular(13);
        _remarkView.delegate = self;
        _remarkView.clipsToBounds = YES;
        _remarkView.textColor = UIColorFromHex(0x000000, 1.0);
        _remarkView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        _remarkView.textContainer.lineFragmentPadding = 0;
        _remarkView.textContainerInset = UIEdgeInsetsMake(15, 9, 15, 9);
        _remarkView.placeholder = @"请输入文字，不少于20汉字；";
        _remarkView.placeholderFont = FONT_Regular(13);
        _remarkView.placeholderColor = [UIColor colorWithHexString:@"#BBBBBB"];
        _remarkView.layer.borderColor = [UIColor colorWithHexString:@"#DDDDDD"].CGColor;
        _remarkView.layer.borderWidth = 1;
        _remarkView.layer.cornerRadius = 8;
        _remarkView.layer.masksToBounds = YES;
        [self.rootContent addSubview:_remarkView];
        RAC(self.viewModel.reqModel, workExplain) = self.remarkView.rac_textSignal;
    }
}

/// 备注图片
- (void)initWithRemarkImageView {
    if (!_remarkImageView) {
        CGRect frame = CGRectMake(0, self.remarkView.bottom + 10, kScreenW, kWDGoutReviewVehicleRemarkImageViewHeight);
        _remarkImageView = [[WDGoutReviewVehicleRemarkImageView alloc] initWithFrame:frame];
        [self.rootContent addSubview:_remarkImageView];
        
        @weakify(self);
        // 更新高度
        _remarkImageView.touchUpdateViewHeightBlock = ^{
            @strongify(self);
            self.rootContent.contentSize = CGSizeMake(kScreenW, self.remarkImageView.bottom + 20);
        };
        // 添加单个图片
        _remarkImageView.viewBlock = ^(id  _Nullable data) {
            @strongify(self);
            [self actionWithAddSign:data];
        };
        // 选择图片
        _remarkImageView.touchChoiceImageVideoBlock = ^{
            @strongify(self);
            [self choiceImageVideo];
        };
    }
    [_remarkImageView updateWithViewData:self.viewModel];
}

- (void)initWithBottomView {
    
    if (![[EDSAppDelegateTool sharedInstance] hasPermission:@(10020302) parentCode:@(100203)]) {
        return;
    }
    
    
    CGRect frame = CGRectMake(0, self.rootContent.bottom, kScreenW, TABBAR_HEIGHT);
    _bottomView = [[WDGoutWaitVehicleBottomView alloc] initWithFrame:frame];
    _bottomView.btnLeftTitle = @"回站维修";
    _bottomView.btnRightTitle = @"开始维修";
    [self.view addSubview:_bottomView];
        @weakify(self);
    _bottomView.viewBlock = ^(id  _Nullable data) {
        @strongify(self);
        if ([data isEqualToString:@"left"]) { // 回站维修
            [self actionWithBackStationMaintenance];
        } else { // 开始维修
            [self actionWithStartMaintain];
        }
    };
}

/// 添加单个图片
/// - Parameter model: model description
- (void)actionWithAddSign:(TYZCommonCellModel *)model {
    self.viewModel.addImageModel = model;
    [self clickedAddImage];
}

/// 上传图片(其它)
/// - Parameter image: image description
- (void)requestWithUploadImages:(NSArray<EDSImageVideoModel *> *)images completion:(RequestCompletionBlock)completion {
    [SVProgressHUD showWithStatus:@"上传中......"];
    self.viewModel.addImageModel = nil;
    NSMutableArray *mutList = [NSMutableArray arrayWithArray:images];
    EDSImageVideoModel *model = mutList.firstObject;
    [mutList removeFirstObject];
    @weakify(self);
    [self.viewModel requestWithUploadImage:model completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            WDUploadFileRspModel *rspModel = respond.data;
            WDTaskFinishInspectFileModel *file = [WDTaskFinishInspectFileModel new];
            file.mediaType = @(model.type);
            file.uploadType = @(6); // 其他；
            file.uploadUrl = rspModel.link;
            [self.viewModel.reqModel.files addObject:file];
            if (mutList.count != 0) {
                [self requestWithUploadImages:mutList.copy completion:completion];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
                if (completion) {
                    completion(respond);
                }
            }
        } else {
            if (mutList.count != 0) {
                [self requestWithUploadImages:mutList.copy completion:completion];
            } else {
                [SVProgressHUD showInfoWithStatus:@"上传失败，请稍后再试！"];
                if (completion) {
                    completion(respond);
                }
            }
        }
    }];
}





/// 回站维修
- (void)actionWithBackStationMaintenance {
    @weakify(self);
    [self.viewModel.reqModel.files removeAllObjects];
    // 判断建议处理方式 是否有选中的
    BOOL ret = NO;
    for (TYZCommonCellModel *ent in self.viewModel.processModes) {
        if (ent.isCheck) {
            ret = YES;
            self.viewModel.reqModel.workResult = ent.title;
            break;
        }
    }
    if (ret == NO) {
        [SVProgressHUD showInfoWithStatus:@"请选择处理方式！"];
        return;
    }
    
    if ([objectNull(self.viewModel.reqModel.workExplain) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入处理说明！"];
        return;
    }
    
    [self.viewModel.reqModel.files removeAllObjects];
    
    // 车辆VIN码照片
    TYZCommonCellModel *model = self.viewModel.remarkImageInfos[0];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车辆VIN码照片！"];
        return;
    }
    // 检查:1VIN码 2车辆仪表 3车头45度 4故障部位 5行驶证 6其他
    WDTaskFinishInspectFileModel *fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(1); // VIN码
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 车辆仪表照片
    model = self.viewModel.remarkImageInfos[1];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车辆仪表照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(2); // 车辆仪表
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    
    // 车头45°照片
    model = self.viewModel.remarkImageInfos[2];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车头45°照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(3); // 车头45度
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 故障部位照片
    model = self.viewModel.remarkImageInfos[3];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传故障部位照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(4); // 故障部位
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 行驶证信息照片
    model = self.viewModel.remarkImageInfos[4];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传行驶证信息照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(5); // 行驶证
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    self.viewModel.reqModel.operateType = @(1); // 回站维修
    if (self.viewModel.dataList.count > 0) {
        [self requestWithUploadImages:self.viewModel.dataList completion:^(EDSRespondDataEntity * _Nonnull respond) {
            @strongify(self);
//            NSArray *files = self.viewModel.reqModel.files;
            [self actionWithStartMaintainScanCode];
        }];
    } else {
        [self actionWithStartMaintainScanCode];
    }
}

/// 开始维修
- (void)actionWithStartMaintain {
    @weakify(self);
    [self.viewModel.reqModel.files removeAllObjects];
    // 判断建议处理方式 是否有选中的
    BOOL ret = NO;
    for (TYZCommonCellModel *ent in self.viewModel.processModes) {
        if (ent.isCheck) {
            ret = YES;
            self.viewModel.reqModel.workResult = ent.title;
            break;
        }
    }
    if (ret == NO) {
        [SVProgressHUD showInfoWithStatus:@"请选择处理方式！"];
        return;
    }
    
    NSString *workExplain = objectNull(self.viewModel.reqModel.workExplain);
    if ([workExplain isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请输入处理说明！"];
        return;
    }
    
    if (workExplain.length > 200) {
        [SVProgressHUD showInfoWithStatus:@"您输入的处理说明超过200个字！"];
        return;
    }
    
    [self.viewModel.reqModel.files removeAllObjects];
    
    // 车辆VIN码照片
    TYZCommonCellModel *model = self.viewModel.remarkImageInfos[0];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车辆VIN码照片！"];
        return;
    }
    // 检查:1VIN码 2车辆仪表 3车头45度 4故障部位 5行驶证 6其他
    WDTaskFinishInspectFileModel *fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(1); // VIN码
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 车辆仪表照片
    model = self.viewModel.remarkImageInfos[1];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车辆仪表照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(2); // 车辆仪表
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    
    // 车头45°照片
    model = self.viewModel.remarkImageInfos[2];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传车头45°照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(3); // 车头45度
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 故障部位照片
    model = self.viewModel.remarkImageInfos[3];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传故障部位照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(4); // 故障部位
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    // 行驶证信息照片
    model = self.viewModel.remarkImageInfos[4];
    if ([objectNull(model.url) isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请上传行驶证信息照片！"];
        return;
    }
    fileModel = [WDTaskFinishInspectFileModel new];
    fileModel.mediaType = @(0);
    fileModel.uploadType = @(5); // 行驶证
    fileModel.uploadUrl = model.url;
    [self.viewModel.reqModel.files addObject:fileModel];
    
    self.viewModel.reqModel.operateType = @(0); // 开始维修
    if (self.viewModel.dataList.count > 0) {
        [self requestWithUploadImages:self.viewModel.dataList completion:^(EDSRespondDataEntity * _Nonnull respond) {
            @strongify(self);
//            NSArray *files = self.viewModel.reqModel.files;
            [self actionWithStartMaintainScanCode];
        }];
    } else {
        [self actionWithStartMaintainScanCode];
    }
}

/// 开始维修进入扫码页面
- (void)actionWithStartMaintainScanCode {
    @weakify(self);
    void(^block)(id data) = ^(id data) {
        @strongify(self);
        if (self.popResultBlock) {
            self.popResultBlock(nil);
        }
    };
    NSDictionary *params = @{
        @"scanTitle": @"扫码维修",
        @"tipInfo": @"将二维码或条形码对准扫码区域，即可自动扫码扫码配件可以确认配件的版本及适配车辆",
        @"serviceModel": self.viewModel.serviceModel,
        @"reqModel": self.viewModel.reqModel,
        @"block":block
    };
    UIViewController *vc = [[TYZRouter sharedInstance] getReviewVehicleScanCodeVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

/// 点击右上角按钮事件 配件扫码
/// - Parameter sender: sender description
- (void)actionWithNavRight:(id)sender
{
    @weakify(self);
    void(^block)(id data) = ^(id data) {
        @strongify(self);
        WDArrivalServiceItemModel *model = data;
        if (model && model.id > 0) {
            [self.navigationController popViewControllerAnimated:NO];
            if (model.taskType == 0) {
                [EDSAppDelegateTool sharedInstance].rootTabBar.selectedIndex = 0;
            } else {
                [EDSAppDelegateTool sharedInstance].rootTabBar.selectedIndex = 1;
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kARRIVAL_SCAN_CODE_SUCCESS_NOTI object:data];
        }
    };
    
    NSDictionary *params = @{
        @"fromWhere": @(2),  // 1 表示来自到站服务；2 表示来自外出救援; 3 到站服务检查中右上角(配件扫码)
        @"scanTitle": @"扫码",
        @"tipInfo": @"将二维码或条形码对准扫码区域，即可自动扫码扫码配件可以确认配件的版本及适配车辆",
        @"block": block
    };
    UIViewController *vc = [[TYZRouter sharedInstance] getServiceScanCodeVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

/// 申请取消
/// - Parameter sender: sender description
- (void)actionWithApplyCancel:(id)sender {
//    [SVProgressHUD showInfoWithStatus:@"取消申请"];
    NSMutableDictionary *params = @{@"serviceModel":self.viewModel.serviceModel}.mutableCopy;
    if (self.popResultBlock) {
        params[@"block"] = self.popResultBlock;
    } else {
        @weakify(self);
        void(^block)(id data) = ^(id data) {
            @strongify(self);
//            [self doRefreshData];
        };
        params[@"block"] = self.popResultBlock;
    }
    
    UIViewController *vc = [[TYZRouter sharedInstance] getServiceCancelWorkOrderVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

/// 工单详情
- (void)actionWithDetail {
    
    if (![[EDSAppDelegateTool sharedInstance] hasPermission:@(10020301) parentCode:@(100203)]) {
        [SVProgressHUD showInfoWithStatus:@"您没有查看详情的权限！"];
        return;
    }
    
    
    NSMutableDictionary *params = @{@"serviceModel":self.viewModel.serviceModel}.mutableCopy;
    @weakify(self);
    void(^block)(id data) = ^(id data) {
        @strongify(self);
//            [self doRefreshData];
    };
    params[@"block"] = block;
    
    UIViewController *vc = [[TYZRouter sharedInstance] getGoutReviewVehicleDetailVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
}

/**
 添加图片
 */
- (void)clickedAddImage
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    // 拍照和视频
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.viewModel.photoType = 1;
        [self openPicOrVideoWithSign];
    }];
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.viewModel.photoType = 0;
        [self openPicOrVideoWithSign];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [alertController addAction:pictureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)openPicOrVideoWithSign
{
    UIImagePickerController *imagePicker = nil;
    if (self.viewModel.photoType == 0)
    {
        //本地相簿
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = NO;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.image", nil];
        imagePicker.delegate = self;
    }
    else
    {
        //相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.allowsEditing = NO;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//            imagePicker.mediaTypes =  [[NSArray alloc] initWithObjects: @"public.image", nil];
            imagePicker.delegate = self;
        }
    }
    if (imagePicker)
    {
        if (@available(iOS 11.0, *))
        {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
        }
        [TYZJumpVCManager presentBaseVC:self presentVC:imagePicker completion:nil];
    }
}

/**
 选择图片提示框
 */
- (void)choiceImageVideo
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    @weakify(self);
    // 拍照和视频
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self cameraImageVideo];
    }];
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self photoAlbumImageVideo];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:videoAction];
    [alertController addAction:pictureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

/**
 从相机获取图片或者视频
 */
- (void)cameraImageVideo
{
//    if (self.viewModel.dataList.count >= 9)
//    {
//        [SVProgressHUD showInfoWithStatus:@"图片最多只能选择9张！"];
//        return;
//    }
    UIViewController *recordVC;
    
    void(^completionBlock)(id model) = ^(EDSImageVideoModel *model) {
//        debugLog(@"图片视频完成==%@", [model modelToJSONString]);
        self.viewModel.libType = model.type;
        
        if ([self hasImageVideo:model.type]) {
            return;
        }
        
        NSArray *list = @[model];
        self.viewModel.imageSize = [self.viewModel getImageSize:model];
        debugLogSizeName(@"image", self.viewModel.imageSize);
        [self.viewModel.dataList addObjectsFromArray:list];
        [self.remarkImageView updateWithViewData:nil];
    };
    
    BOOL isLast = NO; // 上次的是不是图片
//    if (self.viewModel.dataList.count > 0)
//    {
//        EDSImageVideoModel *model = self.viewModel.dataList[0];
//        if (model.type == 0)
//        {// 图片
//            isLast = YES; // 上次的是图片
//        }
//    }
    NSDictionary *param = @{@"second":@(60), @"completionBlock":completionBlock, @"isLastTimeImage":@(isLast), @"type": @(1)};
    
    recordVC = [[TYZRouter sharedInstance] getRecordVideoVC:param];
    TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
    TYZBaseNavigationController *nav = [[TYZBaseNavigationController alloc] initWithRootViewController:recordVC];
    [nav setupNavCommonInfo:navInfo];
    [TYZJumpVCManager presentBaseVC:self presentVC:nav completion:nil];
}

/**
 从相册获取图片或则视频
 */
- (void)photoAlbumImageVideo
{
    
    @weakify(self);
    //相册权限
    [AuthorityManager getPhotoAuthorityWithAgreeAuthority:^(BOOL isAuthorized) {
        @strongify(self);
        if (isAuthorized)
        {
            @weakify(self);
            void(^block)(NSMutableArray *selectPhotoList, int libType) = ^(NSMutableArray *selectPhotoList, int libType) {
                @strongify(self);
                self.viewModel.libType = libType;
                
                if ([self hasImageVideo:libType]) {
                    return;
                }
                
                self.viewModel.imageSize = [self.viewModel getImageSize:selectPhotoList.firstObject];
                [self.viewModel.dataList addObjectsFromArray:selectPhotoList];
                
                NSArray *tmpList = [self.viewModel.dataList copy];
                if (tmpList.count > self.viewModel.addImageVideoNum)
                {// 当出现大雨9个的时候，就只要9个
                    [self.viewModel.dataList removeAllObjects];
                    [self.viewModel.dataList addObjectsFromArray:[tmpList subarrayWithRange:NSMakeRange(0, self.viewModel.addImageVideoNum)]];
                }
                
                [self.remarkImageView updateWithViewData:nil];
            };
            // isSelectImage yes 表示只选择图片；NO表示 选择图片和视频
            NSDictionary *param = @{@"selectPhotoNumType":@(1), @"photoNum":@(self.viewModel.dataList.count), @"isSelectImage":@(NO), @"selectPhotoBlock":block, @"ispush":@(NO)};
            UIViewController *imagePickerVC = [[TYZRouter sharedInstance] getChoiceImagePickerVC:param];
            [TYZJumpVCManager presentBaseVC:self presentVC:imagePickerVC completion:nil];
        }
    }];

}

/// 这里需要判断，上传图片，就不能上传视频，如果需要上传视频，需要先删除图片。视频只能上传一个
/// - Parameter libType: 类型；0表示图片；1表示视频；2表示音频
- (BOOL)hasImageVideo:(NSInteger)libType {
    // 这里需要判断，上传图片，就不能上传视频，如果需要上传视频，需要先删除图片。视频只能上传一个
    NSInteger tmpLibType = (libType == 1 ? 0 : 1);
    BOOL isHas = NO;
    for (EDSImageVideoModel *ent in self.viewModel.dataList) {
        if (ent.type == tmpLibType) {
            isHas = YES;
            break;
        }
    }
    if (isHas) {
        NSString *tip = (tmpLibType == 1 ? @"请先删除视频，再上传图片！" : @"请先删除图片，再上传视频！");
        [SVProgressHUD showInfoWithStatus:tip];
        return YES;
    }
    
    if (libType == 1 && self.viewModel.dataList.count >= 1) { // 视频。视频只能有一个。
        [SVProgressHUD showInfoWithStatus:@"视频只能上传一个！"];
        return YES;
    } else if (libType == 0 && self.viewModel.dataList.count >= self.viewModel.addImageVideoNum) {
        NSString *tip = [NSString stringWithFormat:@"图片最多只能上传%zd个！", self.viewModel.addImageVideoNum];
        [SVProgressHUD showInfoWithStatus:tip];
        return YES;
    }
    return isHas;
}

/// 上传图片
/// - Parameter image: image description
- (void)requestWithUploadImage:(UIImage *)image {
    [SVProgressHUD showWithStatus:@"上传中......"];
    @weakify(self);
    EDSImageVideoModel *model = [EDSImageVideoModel new];
    model.type = 0;
    model.srcImage = image;
    [self.viewModel requestWithUploadImage:model completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
            self.viewModel.addImageModel.image = image;
            [self.remarkImageView updateWithSignImage:self.viewModel.addImageModel];
        } else {
            [SVProgressHUD showInfoWithStatus:@"上传失败，请稍后再试！"];
        }
    }];
}

#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
//    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
//    {
//        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//        CGSize imgSize = image.size;
        
//        if (imgSize.width > 100 )
//        {
//            image = [UIImage imageWithImage:image scaledToSize:CGSizeMake(100, 100)];
//        }
        
        NSData *imgData = UIImageJPEGRepresentation(image, 0.8);
        UIImage *upImage = [[UIImage alloc] initWithData:imgData];
        
        [self requestWithUploadImage:upImage];
        
        
        
//        self.viewModel.base64 = [imgData base64EncodedString];
//        [self requestModifyPhoto];// 提交
//        [self.uploadImageView loadImage:image fileId:@""];
//        [self.uploadArr addObject:image];
//        _rootView.contentSize = CGSizeMake(self.rootView.width, self.uploadImageView.bottom + 10);
//    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}


#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
//    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(kRealValue(343), CGFLOAT_MAX)];
//    CGFloat heigth = sizeToFit.height;
//    [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.detailAddressLabel.mas_bottom).offset(kRealValue(14.5));
//        make.height.mas_equalTo(heigth);
//        make.width.mas_equalTo(kRealValue(343));
//        make.left.equalTo(self.detailAddressLabel.mas_left);
//        make.bottom.equalTo(self.detailAddressView.mas_bottom).offset(-kRealValue(12));
//    }];
}

@end
